#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import oauth
import logging
import urllib, urllib2


from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson
from google.appengine.api import memcache
from util.InitDatabase import InitDatabase
from time import localtime
import string
import random
import ConfigParser
from signed_request import signed_request


webapp.template.register_template_library('japaneseFilter')

CONSUMER_KEY = 'd14883c77ab304ecc255'
CONSUMER_SECRET = 'd4bde3e1d9dfe54679ccac60097bea27147fa4db'
BASE_URL = 'http://api.mixi-platform.com/os/0.8'

def get_person(user_id):
    data = memcache.get('person-%s' % user_id)
    if data is not None:
        return data

    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    params = {'xoauth_requestor_id': user_id,
              'format': 'json',
             }

    request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method='GET',
                  http_url=BASE_URL + '/people/@me/@self',
                  parameters=params,
              )
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

    uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
    r = urllib2.Request(uri, headers=request.to_header())

    try:
        data = simplejson.loads(urllib2.urlopen(r).read())
        memcache.add('person-%s' % user_id, data, 3600)
        return data
    except urllib2.HTTPError, e:
        logging.error(e)
        return False
    except:
        return False

        
class HelloHandler(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        owner_id = self.request.get('opensocial_owner_id')
        page_num = self.request.get('page_num')
        if owner_id:
            person = get_person(owner_id)

        if page_num:
            page = int(page_num) + 1
        else:
            page = 10
            
        template_values = {
            'app_id': self.request.get('opensocial_app_id'),
            'user_info': str(person['entry']) if person else None,
            'page_num':page,
        }

        path = os.path.join(os.path.dirname(__file__), './tmpl/hello.html')
        self.response.out.write(template.render(path, template_values))
        
class HelloHandler2(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        owner_id = self.request.get('opensocial_owner_id')
        page_num = self.request.get('page_num')
  #      if owner_id:
  #          person = get_person(owner_id)

        if page_num:
            page = int(page_num) + 100
        else:
            page = 10
            
        template_values = {
            'app_id': self.request.get('opensocial_app_id'),
            'user_info': 'hoge',
            'page_num':page,
        }

        path = os.path.join(os.path.dirname(__file__), './tmpl/hello2.html')
        self.response.out.write(template.render(path, template_values))

class TestHandler(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        template_values = {
            'app_id': "test",
            'user_info': "userinfo",
        }
  
        path = os.path.join(os.path.dirname(__file__), './tmpl/hello.html')
        self.response.out.write(template.render(path, template_values))

class PlayGame(webapp.RequestHandler):
    def __init__(self):
        #MAX_NUM less than MAX_VALUE
        self.QUESTION_MAX_NUM = 4
        self.QUESTION_MAX_VALUE = 15
        self.SESSION_ID_LENGTH = 8
        self.LUCKY_ITEM_NUM = 50
        self.URL_SETTING_FILE="urlSettings.ini"
        self.MOBILE_TYPE='mobile'
        self.PC_TYPE='pc'
        self.SMARTPHONE_TYPE='smartphone'
        self.URL_CONF=''
        
            
    def get(self):
        ownerID = ""
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        conf = memcache.get('confURL')
        if conf is None:
            conf = self.getURLs(self.URL_SETTING_FILE)
            memcache.add('confURL',conf,60)

        supportBrowser=checkBrowser(self.request.user_agent)
        userAgent=detectAgent(self.request.user_agent)
        if supportBrowser==False:
                template_values={}
                if userAgent == 'android2.1':
                    self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=UTF-8'
                    path = os.path.join(os.path.dirname(__file__), './tmpl/notsupport_u.html')
                else:
                    template_values = {
                        'userAgent': userAgent,
                        'supportBrowserURL':conf.get(userAgent,'supportBrowserURL'),
                        }
                    path = os.path.join(os.path.dirname(__file__), './tmpl/notsupport_o.html')
                self.response.out.write(template.render(path, template_values))
        else:
            nickname = self.request.get('nickname')
            ownerID = self.request.get('opensocial_owner_id')
            if ownerID:
                person = self.getUserInfo(ownerID)
                if person is not None:
                    nickname = person['entry']['nickname']
            player=memcache.get('player-%s' % nickname)
        
            if player == nickname:
                template_values = {
                                   'message': u'今日はすでに診断したのでまた明日遊んでね',
                                   }
                path = os.path.join(os.path.dirname(__file__), './tmpl/message_o.html')
                self.response.out.write(template.render(path, template_values))
            else:
            
                if nickname =='':
                    nickname = 'anonymous'
                
                userAgent=detectAgent(self.request.user_agent)
                sessionID = ownerID + self.createSessionID()
        
                template_values = {
                               'question_num': '0',
                               'session_id': sessionID,
                               'nickname':nickname,
                               'cssURL':conf.get(userAgent,'cssURL'),
                               'gameURL':conf.get(userAgent,'gameURL'),
                               'privacyURL':conf.get(userAgent,'privacyURL'),
#                               'userAgent':self.request.user_agent,
                               'userAgent':userAgent,
                               'supportBrowserURL':conf.get(userAgent,'supportBrowserURL'),
 
                               }
                memcache.add('person-%s' % sessionID,nickname,3600)
                path = os.path.join(os.path.dirname(__file__), './tmpl/top_o.html')
                self.response.out.write(template.render(path, template_values))
        
    def setDayPlayLimitation(self,nickname): 
        times = localtime()
        lastMinutes = (23-times[3])*3600+(59-times[4])*60+(59-times[5])
        #memcache.add('player-%s' % nickname,nickname,lastMinutes)
        #memcache.add('player-%s' % nickname,nickname,60)
        
    def getURLs(self,settingFile):
        conf = ConfigParser.SafeConfigParser()
        conf.read(settingFile)
        return conf
        

    def getUserInfo(self, user_id):
        data = memcache.get('person-%s' % user_id)
        if data is not None:
            return data

        consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
        params = {'xoauth_requestor_id': user_id,
                  'format': 'json',
                  }

        request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method='GET',
                  http_url=BASE_URL + '/people/@me/@self',
                  parameters=params,
              )
        
        request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

        uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
        r = urllib2.Request(uri, headers=request.to_header())

        try:
            data = simplejson.loads(urllib2.urlopen(r).read())
            memcache.add('person-%s' % user_id, data, 3600)
            return data
        except urllib2.HTTPError, e:
            logging.error(e)
            return False
        except:
            return False
        
    
    def createSessionID(self):
        chars = string.ascii_letters + string.digits + '_'
        sessionID = "".join([ random.choice(chars) for i in range(self.SESSION_ID_LENGTH) ])
        return sessionID
    
     
    def post(self):
        gender = self.request.get("gender")
        sessionID = self.request.get("sessionID")
        questionNumStr = self.request.get("questionNum")
        nickname = self.request.get("nickname")

   #     if questionNumStr =='':
   #     questionNum =0
   #     else :
        questionNum = int(questionNumStr)
        
        if questionNum ==0 :
#            userID = self.getUserID()
#            sessionID = self.createSessionID()
#            sessionID = userID + sessionID
            questionIDList = self.createRandomList(self.QUESTION_MAX_NUM, self.QUESTION_MAX_VALUE)
            self.setQuestions(questionIDList, sessionID)
            
        if questionNum >= self.QUESTION_MAX_NUM:
            self.finalizeGame(sessionID, gender, nickname)
        
        else :
            self.retrieveQuestion(sessionID, questionNum, gender, nickname)     
     
    def setQuestions(self, questionIDList, cacheKey):
        i = 0
        questionsList = []
        for qID in questionIDList:
            questions = db.GqlQuery("SELECT * FROM Quiz WHERE questionID= :1 ", str(qID))
            for question in questions:
                questionsList.append(question)
        
        # Store the questionList to memcache with key is userID+sessionID and value is questionList
        memcache.add(key=cacheKey, value=questionsList, time=3600)

    def retrieveQuestion(self, sessionID, questionNum, gender, nickname):
        questionList = memcache.get(sessionID)
        question = questionList[questionNum]
        
        ### Need to modify
      #  userAgent=self.request.user_agent
      #  userAgentID=judgeAgent(userAgent)
      #  postURL=detectPostURL(userAgentID)
        conf = memcache.get('confURL')
        if conf is None:
            conf = self.getURLs(self.URL_SETTING_FILE)
            memcache.add('confURL',conf,60)
        userAgent=detectAgent(self.request.user_agent)
        
        ###
        questionNum = questionNum + 1
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        template_values = {
            'question' : question,
            'questionNum': questionNum,
            'sessionID' : sessionID,
            'gender' : gender,
            'cssURL':conf.get(userAgent,'cssURL'),
            'gameURL':conf.get(userAgent,'gameURL'),
            'userAgent':userAgent,
            'nickname':nickname,
        }
#        if userAgent=="mobile":
#            path = os.path.join(os.path.dirname(__file__), './tmpl/mgame.html')
#        else:
#            path = os.path.join(os.path.dirname(__file__), 'tmpl/game.html')
        path = os.path.join(os.path.dirname(__file__), 'tmpl/game_o.html')
 
        self.response.out.write(template.render(path, template_values))

    def finalizeGame(self, sessionID, gender, nickname):
        gen = "0"
        if gender == "1" :
            gen = "1"
        ratio = random.randint(0, 120)
        level = self.checkLevel(ratio)
        
        # check an existence of the diagnosis in memcach, if this is first time add the data to memcache
#        diagnosis=memcache.get('diagnosis-%s' % str(level))
#        if diagnosis is None:
        diagnoses = db.GqlQuery("SELECT * FROM Diagnosis WHERE levelID = :1 AND gender = :2", level, gen)
        diagnosis = diagnoses.fetch(1)
#            memcache.add('diagnosis-%s' % str(level), diagnosis, 30)
        
        # check an existence of the luckyitem in memcach, if this is first time add the data to memcache        
        luckyNumber = random.randint(0, self.LUCKY_ITEM_NUM - 1)
        luckyitem = memcache.get('luckyItem-%s' % str(luckyNumber))
        if luckyitem is None:
            luckyitems = db.GqlQuery("SELECT * FROM LuckyItem WHERE itemID = :1 ", str(luckyNumber))
            luckyitem = luckyitems.fetch(1)
            memcache.add('luckyItem-%s' % str(luckyNumber), luckyitem, time=129600)
        itemName=luckyitem[0].itemName
        
        
        nickname2=memcache.get('person-%s' % sessionID)
        if nickname2 is None:
            nickname2 =''
            
        ### Need to modify
        #userAgent=self.request.user_agent
        #userAgentID=judgeAgent(userAgent)
        #voiceURL=detectPostURL(userAgentID)
        #inviteURL=voiceURL
        conf = memcache.get('confURL')
        if conf is None:
            conf = self.getURLs(self.URL_SETTING_FILE)
            memcache.add('confURL',conf,60)
        userAgent=detectAgent(self.request.user_agent)
        
        postText=''
        if userAgent != 'mobile':
            postText = unicode(nickname2) + u'さんが今日運命の人に出会える確率'+unicode(ratio)+u'%　ラッキーアイテム:'+itemName
        ###
        
        if ratio > 100:
            ratioBar = 100
        else:
            ratioBar = ratio
        
        
        self.setDayPlayLimitation(nickname) #limitation for play once a day
            
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        template_values = {
            'ratio' : ratio,
            'ratioBar':ratioBar,
            'diagnosisText': diagnosis[0].diagnosisText,
            'itemName' : itemName,
            'nickname' : nickname2,
            'cssURL':conf.get(userAgent,'cssURL'),
            'voiceURL' : conf.get(userAgent,'voiceURL'),
            'inviteURL' :conf.get(userAgent,'inviteURL'),
            'appliURL':conf.get(userAgent,'appliURL'),
            'gameURL':conf.get(userAgent,'gameURL'),
            'postText': postText,
            'userAgent':userAgent,
        }
#        if userAgent=="mobile":
#            path = os.path.join(os.path.dirname(__file__), './tmpl/mresult.html')
#        else:
#            path = os.path.join(os.path.dirname(__file__), 'tmpl/result.html')
        path = os.path.join(os.path.dirname(__file__), 'tmpl/result_o.html')
        self.response.out.write(template.render(path, template_values))

    def checkLevel(self,number):
        levels=[120,99,83,64,42,21,0]
#        levels=[0,21,42,64,83,99,120]
        for x in range(7):
            if number >= levels[x]:
                return 6-x
            
        
    def createRandomList(self, elementMaxNum, elementMaxValue):
        randomNumList = []
        i = 0
        while i < elementMaxNum:
            qid = random.randint(0, elementMaxValue - 1)
            if qid not in randomNumList:
                randomNumList.append(qid)
                i += 1
        return randomNumList
           

class PrivacyPolicy(webapp.RequestHandler):   
            
    def get(self):
        template_values = {}
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'

        path = os.path.join(os.path.dirname(__file__), 'tmpl/privacy_o.html')
        self.response.out.write(template.render(path, template_values))
   
class SupportBrowser(webapp.RequestHandler):   
            
    def get(self):
        template_values = {}
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        path = os.path.join(os.path.dirname(__file__), 'tmpl/supportBrowser_o.html')
        self.response.out.write(template.render(path, template_values))

   
application = webapp.WSGIApplication([
        ('/game', PlayGame), ('/dbutil', InitDatabase), ('/privacy', PrivacyPolicy), ('/browser', SupportBrowser)], debug=True)


def detectAgent(userAgent):
    if userAgent.startswith('DoCoMo'):
        return 'mobile'  
    elif userAgent.startswith('KDDI-'):
        return 'mobile'
    elif userAgent.startswith('SoftBank'):
        return 'mobile'
    elif userAgent.startswith('Vodafone'):
        return 'mobile'
    elif userAgent.startswith('Mozilla/5.0 (Linux; U; Android 2.1'):
        return 'android2.1'
    elif userAgent.startswith('Mozilla/5.0 (iP'):
        return 'smartphone'
    elif userAgent.startswith('Mozilla/5.0 (Li'):
        return 'smartphone'
    else:
        return 'pc'

def checkBrowser(userAgent):
    if userAgent.startswith('Mozilla/5.0 (Linux; U; Android 2.1'):
        return False
    elif userAgent.startswith('Mozilla/5.0 (compatible; MSIE 9.0'):
        return False
    else:
        return True


def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
